<template>
  <div>
    <VolBox :lazy="true" :model.sync="modelFF" title="分房" :width="600" :height="300">
      <VolForm ref="formRules1" :label-width="80" :formFields="formFields1" :formRules="formRules1">
      </VolForm>
      <div slot="footer">
        <Button type="success" @click="submitFF">确认</Button>
        <Button type="default" @click="modelFF = false">关闭</Button>
      </div>
    </VolBox>

    <VolBox :lazy="true" :model.sync="modelYJ" title="押金" :width="400">
      <VolForm ref="formRulesYJ" :label-width="100" :formFields="formFieldsYJ"
        :formRules="formRulesYJ">
      </VolForm>
      <div slot="footer">
        <Button type="default" @click="modelYJ = false">关闭</Button>
      </div>
    </VolBox>

    <VolBox :lazy="true" :model.sync="modelBZ" title="备注" :width="300">
      <VolForm ref="formRulesBZ" :label-width="80" :formFields="formFieldsBZ"
        :formRules="formRulesBZ">
      </VolForm>
      <div slot="footer">
        <Button type="success" @click="submitBZ">确认</Button>
        <Button type="default" @click="nomodol">关闭</Button>
      </div>
    </VolBox>

    <VolBox :lazy="true" :model.sync="modelXD" title="手工下单" :width="700" :height="400">
      <VolForm ref="formRulesXD" :label-width="100" :formFields="formFieldsXD"
        :formRules="formRulesXD">
      </VolForm>
      <div slot="footer">
        <Button type="success" @click="submitXD">确认</Button>
        <Button type="default" @click="modelXD = false">关闭</Button>
      </div>
    </VolBox>

    <VolBox :lazy="true" :model.sync="modelCPJG" title="产品价格" :width="400">
      <VolForm ref="formRulePro" :label-width="100" :formFields="formFieldsPro"
        :formRules="formRulePro">
      </VolForm>
      <div slot="footer">
        <Button type="default" @click="modelCPJG = false">关闭</Button>
      </div>
    </VolBox>
  </div>
</template>

<script>
import VolBox from "@/components/basic/VolBox.vue";
import VolForm from "@/components/basic/VolForm.vue";
import VolTable from "@/components/basic/VolTable.vue";
export default {
  name: "CampHouseOrderBox",
  components: {
    VolBox,
    VolForm,
    VolTable,
  },
  data() {
    return {
      modelFF: false,
      formFields1: {
        YF: "",
        YW: "",
      },
      formRules1: [
        [
          {
            title: "营房",
            field: "YF",
            type: "select",
            dataKey: "",
            data: [],
            required: true,
            onChange: (n) => {
              this.formFields1.YW = "";
              this.formRules1[1][0].data = this.YWLIST.filter((i) => {
                if (i.chid == n) return i;
              }).map((j) => {
                return {
                  key: j.id,
                  value: j.code,
                };
              });
            },
          },
        ],
        [
          {
            title: "营位",
            field: "YW",
            type: "select",
            dataKey: "",
            data: [],
            required: true,
          },
        ],
      ],
      modelYJ: false,
      formFieldsYJ: {
        yj: "",
        authcode: "",
        pay_code: "",
      },
      formRulesYJ: [
        [
          {
            title: "押金",
            field: "yj",
            type: "text",
            disabled: true,
          },
        ],
        [
          {
            title: "支付方式",
            required: true,
            field: "pay_code",
            type: "select",
            dataKey: "",
            data: [],
          },
        ],
        [
          {
            title: "扫码",
            field: "authcode",
            type: "text",
            onKeyPress: ($event) => {
              if ($event.keyCode == 13) {
                this.submitYJ();
              }
            },
          },
        ],
      ],
      ZCDetail: [],
      CampsiteLeaseList: [],
      ywid: 0,
      CampsiteLeaseWhere: "",
      YJDetailList: [],
      YWLIST: [],
      modelBZ: false,
      formFieldsBZ: {
        notes: "",
      },
      formRulesBZ: [
        [
          {
            title: "备注",
            field: "notes",
            type: "text",
            required: true,
          },
        ],
      ],
      disBOX: {},
      modelXD: false,
      formFieldsXD: {
        bookingName: "",
        bookingPhone: "",
        bookingIdCard: "",
        bookingType: "",
        unitId: "",
        houseType: "",
        reservationType: "",
        isReserve: 0, // 0,1
        isHouseDeposit: 0, //0,1
        goodsId: "",
        discount: "",
        discountRemark: "",
      },
      formRulesXD: [
        [
          { title: "姓名", required: true, field: "bookingName", type: "text" },
          {
            title: "手机号",
            required: true,
            field: "bookingPhone",
            type: "phone",
          },
          {
            title: "证件类型",
            required: true,
            field: "bookingType",
            type: "select",
            dataKey: "",
            data: [],
          },
        ],
        [
          {
            title: "证件号",
            required: true,
            field: "bookingIdCard",
            type: "text",
          },
          {
            title: "单位",
            required: true,
            field: "unitId",
            type: "select",
            dataKey: "",
            data: [],
          },
        ],
        [
          {
            title: "营房类型",
            required: true,
            field: "type",
            type: "select",
            dataKey: "",
            data: [],
          },
          {
            title: "营位房型",
            required: true,
            field: "houseType",
            type: "select",
            dataKey: "",
            data: [],
          },
          {
            title: "营房产品",
            required: true,
            field: "goodsId",
            type: "select",
            dataKey: "",
            data: [],
          },
        ],
        [
          {
            title: "折扣",
            field: "discount",
            type: "text",
            extra: {
              tooltip: true,
              content: "折扣取值范围应在0~1之间",
            },
          },
          {
            title: "折扣备注",
            field: "discountRemark",
            type: "text",
          },
        ],
      ],
      CampHouseSellList: [],
      modelCPJG: false,
      formFieldsPro: {
        pay_code: "",
        Authcode: "",
      },
      formRulePro: [
        [
          {
            title: "支付方式",
            required: true,
            field: "pay_code",
            type: "select",
            dataKey: "",
            data: [],
          },
        ],
        [
          {
            title: "扫码",
            field: "Authcode",
            type: "text",
            onKeyPress: ($event) => {
              if ($event.keyCode == 13) {
                this.submitCPJG();
              }
            },
          },
        ],
      ],
      AddPayForm: {},
      repeatPay: 0,
      outTradeNo: ''
    };
  },
  watch: {
    "formFieldsXD.unitId": {
      handler(n, o) {
        this.GetHouseType(n, this.formFieldsXD.type);
      },
    },
    "formFieldsXD.type": {
      handler(n, o) {
        this.GetHouseType(this.formFieldsXD.unitId, n);
      },
    },
    "formFieldsXD.houseType": {
      handler(n, o) {
        this.GetCampHouseSell(n);
      },
    },
  },
  methods: {
    GetCampHouseSell(v) {
      this.formFieldsXD.goodsId = "";
      let goodsId = this.getFormOption("goodsId");
      let parma = {
        order: "desc",
        page: 1,
        rows: 30,
        sort: "id",
        wheres: `[{\"name\":\"unitId\",\"value\":\"${this.formFieldsXD.unitId}\",\"displayType\":\"text\"},{\"name\":\"parentId\",\"value\":\"${this.formFieldsXD.type}\",\"displayType\":\"text\"},{\"name\":\"typeId\",\"value\":\"${v}\",\"displayType\":\"text\"},]`,
      };
      this.http.post("/api/CampHouseSell/getPageData", parma).then((res) => {
        if (res.rows) {
          this.CampHouseSellList = res.rows;
          goodsId.data = res.rows.map((j) => {
            return {
              key: j.id,
              value: j.name,
            };
          });
        }
      });
    },
    GetHouseType(code, type) {
      this.formFieldsXD.goodsId = "";
      let houseType = this.getFormOption("houseType");
      if (code && type) {
        let parma = {
          code: code,
          type: type,
        };
        this.http.get("/api/CampHouseType/GetHouseType", parma).then((res) => {
          if (res.data) {
            houseType.data = res.data.map((j) => {
              return {
                key: j.id,
                value: j.name,
              };
            });
          }
        });
      }
    },
    getFormOption(field) {
      let option;
      this.formRulesXD.forEach((x) => {
        x.forEach((item) => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    getFormOptionCPJG(field) {
      let option;
      this.formRulePro.forEach((x) => {
        x.forEach((item) => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    getFormRulesYJ(field) {
      let option;
      this.formRulesYJ.forEach((x) => {
        x.forEach((item) => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    openXD() {
      console.log(this.getStartDate(new Date()));
      this.modelXD = true;
      let unitId = this.getFormOption("unitId");
      let type = this.getFormOption("type");
      let bookingType = this.getFormOption("bookingType");
      this.http.get("/api/CampHouseUnit/GetCampUnit").then((res) => {
        unitId.data = res.data.list.map((i) => {
          return {
            key: i.code,
            value: i.name,
          };
        });
      });
      this.http
        .post("/api/Dictionary/GetVueDictionary", [
          "CampsiteHouseType",
          "certificate_type",
        ])
        .then((res) => {
          res.forEach((i) => {
            if (i.dicNo == "CampsiteHouseType") {
              type.data = i.data;
            } else if (i.dicNo == "certificate_type") {
              bookingType.data = i.data;
            }
          });
        });
    },
    getStartDate(e) {
      const Y = e.getFullYear(); // 年
      const M = this.prefixZero(e.getMonth() + 1); // 月
      const D = this.prefixZero(e.getDate()); // 日
      const H = this.prefixZero(e.getHours()); // 时
      const Mi = this.prefixZero(e.getMinutes()); // 分
      const S = this.prefixZero(e.getSeconds()); // 秒
      return Y + "-" + M + "-" + D + " " + H + ":" + Mi + ":" + S;
    },

    prefixZero(num = 0, n = 2) {
      // 数字位数不够，数字前面补零
      return (Array(n).join("0") + num).slice(-n);
    },
    submitXD() {
      this.$refs.formRulesXD.validate(() => {
        let cp = this.CampHouseSellList.filter((i) => {
          if (this.formFieldsXD.goodsId == i.id) {
            return i;
          }
        });
        let parma = {
          startTime: cp[0].startTime,
          endTime: cp[0].endTime,
          parentId: cp[0].parentId,
          houseType: this.formFieldsXD.houseType,
          use_date: this.getStartDate(new Date()),
          dayNum: cp[0].dayNum,
        };

        this.http
          .post("/api/CampHouseOrder/GetHouseInventory", parma)
          .then((res) => {
            if (res.status) {
              if (res.data > 0) {
                let parmas = {
                  mainData: {
                    ...this.formFieldsXD,
                    orderPrice: cp[0].Price,
                  },
                  detailData: null,
                  delKeys: null,
                };

                this.http
                  .post("/api/CampHouseOrder/PlaceOrder", parmas)
                  .then((res) => {
                    if (res.status) {
                      this.modelXD = false;
                      this.GetMerchantPayInfo(res.data.data);
                    }
                  });
              } else {
                this.$Message.error("房间数量不够，请选择其他房间");
              }
            }
          });
      });
    },
    GetMerchantPayInfo(e) {
      this.modelCPJG = true;
      this.AddPayForm = {
        orderNumber: e.parentNumber,
      };
      this.formFieldsPro.pay_code = "";
      this.formFieldsPro.Authcode = "";
      let pay_code = this.getFormOptionCPJG("pay_code");
      let parma = {
        unitCode: e.unitId,
      };
      this.http
        .get("/api/CampHouseOrder/GetMerchantPayInfo", parma)
        .then((res) => {
          pay_code.data = res.data.map((i) => {
            return {
              key: i.code,
              value: i.name,
            };
          });
        });
    },
    submitCPJG() {
      this.$refs.formRulePro.validate(() => {
        let parma = {
          ...this.AddPayForm,
          ...this.formFieldsPro,
        };
        this.http.post("/api/CampHouseOrder/AddPay", parma).then((res) => {
          if (res.status) {
            this.modelXD = false;
            this.modelCPJG = false;
            this.$Message.success("支付成功");
            this.$store.getters.data().viewPageTest.refresh();
          } else {
            if (res.data) {
              // 未知 1 失败 2
              if (res.data == 1) {
                let orderTime = setInterval(() => {
                  let parmaw = {
                    orderNumber: this.AddPayForm.orderNumber,
                    pay_code: this.formFieldsPro.pay_code,
                  };
                  this.http
                    .post("/api/CampHouseOrder/OrderQuery", parmaw)
                    .then((res) => {
                      if (res.status) {
                        this.modelXD = false;
                        this.modelCPJG = false;
                        this.$Message.success("支付成功");
                        clearInterval(orderTime);
                        this.$store.getters.data().viewPageTest.refresh();
                      } else {
                        this.$Message.error(res.message);
                      }
                    });
                }, 2000);
                setTimeout(() => {
                  clearInterval(orderTime);
                }, 60 * 1000);
              } else {
                this.$Message.error(res.message);
              }
            }
            this.$Message.error(res.message);
          }
        });
      });
    },
    openBZ(e) {
      this.modelBZ = true;
      this.disBOX = e;
    },
    submitBZ() {
      let parma = {
        mainData: {
          houseId: this.disBOX.chid,
          houseItemId: this.disBOX.id,
          type: 5,
          time: new Date(),
          remark: this.formFieldsBZ.notes,
        },
        detailData: null,
        delKeys: null,
      };
      this.http.post("/api/CampHouseHistory/Add", parma).then((res) => {
        if (res.status) {
          let parmas = {
            mainData: {
              ...this.disBOX,
            },
            detailData: null,
            delKeys: null,
          };
          this.http
            .post("/api/CampsiteHouseItem/Update", parmas)
            .then((res) => {
              if (res) {
                this.modelBZ = false;
                this.$Message.success("保存成功");
              } else {
                this.$Message.error(res.message);
              }
            });
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    nomodol() {
      this.$store.getters
        .data()
        .viewPageTest.$refs.detail.rowData.forEach((i) => {
          if (this.disBOX.id == i.id) {
            i.status = true;
            this.modelBZ = false;
          }
        });
    },
    CampsiteHouse() {
      let v = new Promise((resolve, reject) => {
        let parma = {
          page: 1,
          rows: 30,
          sort: "modifyDate",
          order: "id",
          wheres: "[]",
        };
        this.http.post("/api/CampsiteHouse/getPageData", parma).then((res) => {
          this.formRules1[0][0].data = res.rows.map((i) => {
            return {
              key: i.id,
              value: i.name,
            };
          });
          resolve(this.formRules1[0][0].data);
        });
      });
      return v;
    },
    CampsiteHouseItem() {
      let v = new Promise((resolve, reject) => {
        let parmas = {
          page: 1,
          rows: 30,
          sort: "modifyDate",
          order: "id",
          wheres: `[{\"name\":\"orderNumber\",\"value\":\"${this.ZCDetail.orderNumber}\",\"displayType\":\"text\"}]`,
        };
        this.http
          .post("/api/CampsiteHouseItem/getPageData", parmas)
          .then((res) => {
            if (res.rows.length == 1) {
              this.formFields1.YF = res.rows[0].chid;
              this.formFields1.YW = res.rows[0].id;
              this.ywid = res.rows[0].id;
              resolve(res.rows[0]);
            } else {
              reject(res.rows);
            }
          });
      });
      return v;
    },
    CampsiteLease() {
      let v = new Promise((resolve, reject) => {
        let parma = {
          page: 1,
          rows: 30,
          sort: "modifyDate",
          order: "id",
          wheres: this.CampsiteLeaseWhere,
        };
        this.http.post("/api/CampsiteLease/getPageData", parma).then((res) => {
          this.formRules1[1][0].data = res.rows.map((i) => {
            return {
              key: i.id,
              value: i.code,
            };
          });
          this.formFields1.YW = this.ywid;
          this.CampsiteLeaseList = res.rows;
          resolve(this.formFields1);
        });
      });
      return v;
    },
    openFF(e, v) {
      this.modelFF = true;
      this.ZCDetail = e;
      this.YWLIST = [];
      let parma = {
        HouseType: e.houseType,
      };
      this.http.get("/api/CampHouseOrder/GetHouselist", parma).then((res) => {
        if (res.status) {
          this.formRules1[0][0].data = res.data.map((i) => {
            return {
              key: i.id,
              value: i.name,
            };
          });
          res.data.forEach((i) => {
            if (i.campsiteHouseItems) {
              i.campsiteHouseItems.forEach((j) => {
                this.YWLIST.push(j);
              });
            }
          });
        } else {
          this.$Message.error(res.message);
        }
      });
      this.CampsiteHouseItem()
        .then((res) => {
          this.YWLIST.push(res);
          this.formRules1[1][0].data = this.YWLIST.filter((i) => {
            if (i.chid == this.formFields1.YF) return i;
          }).map((j) => {
            return {
              key: j.id,
              value: j.code,
            };
          });
          this.formFields1.YW = this.ywid;
        })
        .catch((err) => {});
    },
    submitFF() {
      this.$refs.formRules1.validate(() => {
        let parma = {
          id: this.formFields1.YW,
          type: 0,
          chId: this.formFields1.YF,
          orderNumber: this.ZCDetail.parentNumber,
          childOrderNumber: [this.ZCDetail.orderNumber],
        };
        this.http
          .post("/api/CampHouseOrder/ReserveHouse", parma)
          .then((res) => {
            if (res.status) {
              this.modelFF = false;
              this.$Message.success("分房成功");
              this.$store.getters.data().viewPageTest.refresh();
            } else {
              this.$Message.error(res.message);
            }
          });
      });
    },
    openYJ(e, n) {
      this.YJDetailList = e;
      this.formFieldsYJ.sm = "";
      this.formFieldsYJ.pay_code = "";
      let pay_code = this.getFormRulesYJ("pay_code");
      let parma = {
        unitCode: e[0].unitId,
      };
      this.http
        .get("/api/CampHouseOrder/GetMerchantPayInfo", parma)
        .then((res) => {
          pay_code.data = res.data.map((i) => {
            return {
              key: i.code,
              value: i.name,
            };
          });
        });
      if (n == 0) {
        this.formFieldsYJ.yj = 0;
        let status = new Promise((resolve, reject) => {
          var promises = [];
          for (var i = 0; i < e.length; i++) {
            this.ZCDetail = e[i];
            promises.push(this.CampsiteHouseItem());
          }

          Promise.all(promises)
            .then((results) => {
              resolve(results);
            })
            .catch((error) => {
              reject(error);
            });
        });
        status
          .then((res) => {
            res.forEach((i) => {
              this.formFieldsYJ.yj += i.depositPrice;
            });
            this.modelYJ = true;
          })
          .catch((err) => {
            this.$Message.error("还有订单没有分房");
          });
      } else {
        this.ZCDetail = e[0];
        this.formFieldsYJ.yj = "";
        this.CampsiteHouseItem()
          .then((res) => {
            this.modelYJ = true;
            this.formFieldsYJ.yj = res.depositPrice;
          })
          .catch((err) => {
            this.$Message.error("此订单没有分房");
          });
      }
    },
    submitYJ() {
      let childOrderNumber = this.YJDetailList.map((i) => {
        return i.orderNumber;
      });
      let parma = {
        orderNumber: this.ZCDetail.parentNumber,
        childOrderNumber: childOrderNumber,
        authcode: this.formFieldsYJ.authcode,
        pay_code: this.formFieldsYJ.pay_code,
      };
      this.http.post("/api/CampHouseOrder/AddDeposit", parma).then((res) => {
        if (res.status) {
          let parmaa = {
            orderNumber: this.ZCDetail.parentNumber,
            childOrderNumber: childOrderNumber,
            authcode: this.formFieldsYJ.authcode,
            pay_code: this.formFieldsYJ.pay_code,
            repeatPay: this.YJDetailList[0].status == 2 ? 1 : 0,
          };
          this.http
            .post("/api/CampHouseOrder/PayHouseDeposit", parmaa)
            .then((res) => {
              this.outTradeNo = res.results.outTradeNo
              if (res.status) {
                this.modelYJ = false;
                this.$Message.success("入账成功");
                this.WriteoffInterface(childOrderNumber);
                this.$store.getters.data().viewPageTest.refresh();
              } else {
                if (res.data) {
                  // 未知 1 失败 2
                  if (res.data == 1) {
                    let orderTime = setInterval(() => {
                      let parmaw = {
                        orderNumber: this.ZCDetail.parentNumber,
                        childOrderNumber: childOrderNumber,
                        outTradeNo: this.outTradeNo
                      };
                      this.http
                        .post("/api/CampHouseOrder/DepositHouseQuery", parmaw)
                        .then((res) => {
                          if (res.status) {
                            this.modelYJ = false;
                            this.$Message.success("入账成功");
                            this.WriteoffInterface(childOrderNumber);
                            clearInterval(orderTime);
                            this.$store.getters.data().viewPageTest.refresh();
                          } else {
                            this.$Message.error(res.message);
                          }
                        });
                    }, 2000);
                    setTimeout(() => {
                      clearInterval(orderTime);
                    }, 60 * 1000);
                  } else {
                    this.$Message.error(res.message);
                  }
                }
                this.$Message.error(res.message);
              }
            });
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    WriteoffInterface(v) {
      let parmas = {
        page: 1,
        rows: 30,
        sort: "modifyDate",
        order: "id",
        wheres: `[{\"name\":\"orderNumber\",\"value\":\"${v}\",\"displayType\":\"text\"}]`,
      };
      this.http
        .post("/api/CampsiteHouseItem/getPageData", parmas)
        .then((res) => {
          if (res.rows.length == 1) {
            let parma = {
              id: res.rows[0].id,
              type: 1,
              chId: res.rows[0].chid,
              orderNumber: this.ZCDetail.parentNumber,
              childOrderNumber: [res.rows[0].orderNumber],
            };
            this.http
              .post("/api/CampHouseOrder/OrderWriteOff", parma)
              .then((res) => {
                if (res.status) {
                  this.$Message.success("核销成功");
                  this.$store.getters.data().viewPageTest.refresh();
                } else {
                  this.$Message.error(res.message);
                }
              });
          }
        });
    },
  },
};
</script>
<style scoped>
.bot10 {
  margin-bottom: 10px;
}
</style>
